package com.shuhe.metastore;

import com.shuhe.JettyServer;
import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

public class MetaMysql {

    private static Logger logger = Logger.getLogger(MetaMysql.class);

    private static String url = JettyServer.globalProperties.getProperty("meta.url");
    private static String username = JettyServer.globalProperties.getProperty("meta.user");
    private static String password = JettyServer.globalProperties.getProperty("meta.password");
    private static String driver = JettyServer.globalProperties.getProperty("meta.driver");


    public static ResultSet querySql(Connection conn, String sql) throws Exception {
        //logger.info(sql);
        return conn.createStatement().executeQuery(sql);
    }


    public static Connection connect() throws Exception {
        Class.forName(driver);
        return DriverManager.getConnection(url, username, password);
    }

    public static Connection connectByAll(String url, String username, String password, String driver) throws Exception {
        Class.forName(driver);
        return DriverManager.getConnection(url, username, password);
    }


    public static int execSql(Connection conn, String sql) throws Exception {
        //logger.info(sql);
        return conn.createStatement().executeUpdate(sql);
    }

    public static int batchExecSql(Connection conn, ArrayList<String> sqls) throws Exception {
        Statement stat = conn.createStatement();
        for (int i = 0; i < sqls.size(); i++) {
            String sql = sqls.get(i);
            //logger.info(sql.substring(0, sql.length() > 500 ? 500 : sql.length()));
            stat.addBatch(sql);
        }
        stat.executeBatch();
        return 0;
    }

}
